// 方式二
function findMedianSortedArrays(nums1, nums2) {
  const mergeArr = getArrbyMerge(nums1, nums2);
  const len = mergeArr.length;
  const midLeft = Math.floor(len / 2);
  const midRight = Math.ceil(len / 2);
  if (midLeft === midRight) {
    return (mergeArr[midLeft - 1] + mergeArr[midRight]) / 2;
  }
  return mergeArr[midLeft];
  // 合并两个升序数组为一个升序数组
  function getArrbyMerge(target, source) {
    let ret = [];
    const targetLen = target.length;
    const sourceLen = source.length;
    let targetIndex = 0;
    let sourceIndex = 0;
    while (targetIndex < targetLen || sourceIndex < sourceLen) {
      if (targetIndex < targetLen && sourceIndex < sourceLen) {
        const element =
          source[sourceIndex] < target[targetIndex]
            ? source[sourceIndex++]
            : target[targetIndex++];
        ret.push(element);
      } else if (targetIndex < targetLen) {
        ret.push(target[targetIndex]);
        targetIndex++;
      } else if (sourceIndex < sourceLen) {
        ret.push(source[sourceIndex]);
        sourceIndex++;
      }
    }
    return ret;
  }
}

const ret = findMedianSortedArrays([1, 3], [2, 4]);

console.log(ret);
